package com.yp.domain.service.impl;

import com.yp.domain.entity.User;
import com.yp.domain.repository.UserRedis;
import com.yp.domain.repository.UserRepository;
import com.yp.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by CrazyMouse on 2016/12/29.
 */

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserRedis userRedis;

    private static final String keyHead = "mysql:get:user:";

    @Override
    public User findById(int id) {
        User user = userRedis.get(keyHead+id);
        if (user == null) {
            user = userRepository.findOne(id);
            if (user != null) {
                userRedis.add(keyHead+id, 30L, user);
            }
        }
        return user;
    }

    @Override
    public User create(User user) {
        User newUser = userRepository.save(user);
        if (newUser != null) {
            userRedis.add(keyHead+newUser.getId(), 30L, newUser);
        }
        return newUser;
    }

    @Override
    public User update(User user) {
        if (user != null) {
            userRedis.delete(keyHead+user.getId());
            userRedis.add(keyHead+user.getId(), 30L, user);
        }
        return userRepository.save(user);
    }

    @Override
    public void delete(int id) {
        userRedis.delete(keyHead+id);
        userRepository.delete(id);
    }
}
